package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
    // 1 查询所有的1级分类

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        System.out.println(categoryEntities);
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }
    //index/json/catalog.json

    /**
     * 首页三级分裂
     *
     * @return
     */
    @ResponseBody
    @GetMapping("index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> cataLogJson(){
        return categoryService.cataLogJson();
    }




    @ResponseBody
    @GetMapping("index/hello")
    public String hello(){
        //获取一把锁，只要锁名字一样就是同一把锁
        RLock lock = redissonClient.getLock("my_lock");
        String cate1 = (String)redisTemplate.opsForValue().get("cate");
        if(!StringUtils.isEmpty(cate1)){
            return "hello world";
        }
//        lock.lock();//阻塞性等待，默认加锁时间是30s

        lock.lock(10,TimeUnit.SECONDS);
        //问题：lock.lock 锁到期以后 不会自动续期
        String cate = (String)redisTemplate.opsForValue().get("cate");
        if(!StringUtils.isEmpty(cate)){
            return "hello world";
        }
        //
        //1) 锁会自动续期，如果业务长，运行期间自动给锁续上30s（自测是每10s如果不释放锁自动加到30s）,不用担心业务过长
        //2) 加锁的业务只要运行完成，就不会给当前锁续期，即时不手动加锁，锁也会默认30s以后自动删除
        try {
            System.out.println("加锁成功执行业务...."+Thread.currentThread().getId());
            Thread.sleep(300);
            redisTemplate.opsForValue().set("cate","abc");
        }catch (Exception e){

        }finally {
            //3、解锁
            System.out.println("释放锁"+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello world";
    }

    //保证一定读到最新数据，修改期间，写锁是一个排他锁（互斥锁），读锁是一个共享锁
    @GetMapping("write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();//写锁
        try {
            rLock.lock();//阻塞等待  获取锁成功才往下走
            System.out.println("写锁加锁成功");
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.readLock();
        try {
            rLock.lock();//如果有写锁就会阻塞等待 直到写锁释放

            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @RequestMapping("lockdoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch latch = redissonClient.getCountDownLatch("anyCountDownLatch");//anyCountDownLatch必须是同一把锁
        latch.trySetCount(5);//等待5个闭锁都完成
        latch.await();

        return "lockdoor";
    }

    @RequestMapping("go")
    @ResponseBody
    public String go(){
        // 在其他线程或其他JVM里
        RCountDownLatch latch = redissonClient.getCountDownLatch("anyCountDownLatch");
        latch.countDown();//每次减去1 减到1就不减了 也不会报错

        return "go";
    }


}
